<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Plugins\PluginInfo;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';
    protected $username = 'login';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function username()
    {
        return 'login';
    }

    // 账号禁用, 渠道到期
    protected function authenticated(Request $request, $user)
    {
        $company = Company::withTrashed()->find($user->company_id);
        // 渠道时间到期, 禁止改渠道下账号登录 todo: 后期改为脚本
        $endDate = $company->endDate;
        if ($endDate != null) {
            $datetime = $endDate->toDateTime();
            $datetime = strtotime($datetime->format('r'));
            if ($datetime < time()) {
                $session = $request->session();
                $session->clear();
                return view("errors.disable", ['time'=>5, 'msg'=>'使用时间到期']);
            }
        }
        if ($user->status == 0 || (isset($company->deleted_at) && !is_null($company->deleted_at))) {
            $session = $request->session();
            $session->clear();
            return view("errors.disable", ['time'=>5, 'msg'=>'您的账号已经被禁用']);
        }
    }

    protected function credentials(Request $request) {
        $login = $request->input('login');
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';
        return [
            $field => $login,
            'password' => $request->input('password'),
        ];
    }
}
